<template>
  <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
    <!-- 数据列表 -->
    <a-row class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden">
      <!-- 查询条件 -->
      <a-row v-if="showSearchRow" class="w-full">
        <a-form :model="searchForm" label-align="left" layout="inline" size="small">
          <a-form-item field="townName" label="镇街名称">
            <a-input v-model="searchForm.townName" placeholder="镇街名称"/>
          </a-form-item>
          <a-form-item field="status" label="镇街账号状态">
            <a-select
                v-model="searchForm.status"
                allow-clear
                placeholder="镇街账号状态"
            >
              <a-option
                  v-for="(d, index) in dicts[proxy.DICT.commonNumberStatus]"
                  :key="index"
                  :label="d.dictValue"
                  :value="d.dictKey"
              />
            </a-select>
          </a-form-item>
        </a-form>
        <a-row class="w-full mt-2" justify="center">
          <a-space>
            <a-button type="primary" @click="getPageList(false)">
              <template #icon>
                <icon-search/>
              </template>
              <template #default>查询</template>
            </a-button>
            <a-popconfirm
                :popup-visible="deleteConfirmVisible"
                content="确定删除选中镇街账号吗?"
                type="warning"
                @cancel="onDeleteConfirmCancel"
                @ok="onDeleteConfirmOK"
            >
              <a-button
                  status="danger"
                  type="primary"
                  @click="deleteBtnClick(selectedKeys)"
              >
                <template #icon>
                  <icon-delete/>
                </template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
            <a-button @click="getPageList(true)">
              <template #icon>
                <icon-sync/>
              </template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-row>
      </a-row>

      <!-- 分割线 -->
      <a-divider v-if="showSearchRow" class="mt-2"/>

      <!-- 数据操作区 -->
      <a-row class="w-full flex justify-between">
        <a-space>
          <!-- 添加 -->
          <a-button
              size="small"
              type="primary"
              @click="addBtnClick()"
          >
            <template #icon>
              <icon-plus/>
            </template>
            <template #default>添加</template>
          </a-button>
        </a-space>
        <a-space>
          <!-- 刷新 -->
          <a-button shape="circle" size="small" @click="getPageList(false)">
            <template #icon>
              <icon-refresh/>
            </template>
          </a-button>
          <!-- 收缩/展开 -->
          <a-button shape="circle" size="small" @click="showSearchRow = !showSearchRow">
            <template #icon>
              <icon-caret-up v-if="showSearchRow"/>
              <icon-caret-down v-else/>
            </template>
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据展示区 -->
      <a-row class="w-full flex-1 mt-3 overflow-y-auto">
        <a-table
            :columns="datatable.columns"
            :data="datatable.records"
            :loading="datatable.loading"
            :pagination="false"
            :row-selection="rowSelection"
            :scroll="{ minWidth: 600, y: '100%' }"
            class="w-[100%]"
            row-key="townAccountId"
            table-layout-fixed
        >
          <template #townName="{ record }">
            <a-link icon @click="detailBtnClick(record.townAccountId)">{{ record.townName }}</a-link>
          </template>
          <!-- 镇街账号状态 -->
          <template #status="{ record }">
            <dict-convert
                :dict-data="dicts[proxy.DICT.commonNumberStatus]"
                :dict-key="record.status"
            />
          </template>
          <!-- 操作 -->
          <template #operation="{ record }">
            <a-button
                size="mini"
                type="text"
                @click="updateBtnClick(record.townAccountId)"
            >
              <template #icon>
                <icon-edit/>
              </template>
              <template #default>修改</template>
            </a-button>
            <a-popconfirm
                content="确认要删除吗?"
                @ok="deleteBtnOkClick(record.townAccountId)"
            >
              <a-button
                  size="mini"
                  status="danger"
                  type="text"
              >
                <template #icon>
                  <icon-delete/>
                </template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </a-row>

      <!-- 分页 -->
      <a-row class="w-full flex justify-end mt-2">
        <pagination
            v-if="datatable.total > 0"
            v-model:page-num="searchForm.pageNum"
            v-model:page-size="searchForm.pageSize"
            :total="datatable.total"
            @pagination="getPageList(false)"
        />
      </a-row>
    </a-row>

    <a-modal
        v-model:visible="modal.visible"
        :esc-to-close="false"
        :footer="false"
        :mask-closable="false"
        draggable
        width="1000px"
    >
      <template #title>{{ modal.title }}</template>
      <component
          :is="modal.component"
          v-if="modal.visible"
          :params="modal.params"
          @cancel="onCancel"
          @ok="onOk"
          @edit="onEdit"
      />
    </a-modal>
  </a-card>
</template>

<script setup>
import {getCurrentInstance, reactive, ref, shallowRef} from "vue";
import TownAccountDetail from "./TownAccountDetail.vue";
import TownAccountEdit from "./TownAccountEdit.vue";

//全局实例
const {proxy} = getCurrentInstance();
//加载字典
const dicts = proxy.LoadDicts([proxy.DICT.commonNumberStatus]);
//是否展示搜索区域
const showSearchRow = ref(true);
//表格选中数据
const selectedKeys = ref([]);
//表格选中
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: true,
});
//删除确认弹窗 -> 确认
const deleteConfirmVisible = ref(false);

// 模拟数据
const mockTownData = [
  {
    townAccountId: "1",
    townName: "安海镇",
    townPerson: "张三",
    townMobile: "13800138001",
    status: 1,
    createTime: "2024-01-15 10:30:00",
    updateTime: "2024-01-20 14:20:00"
  },
  {
    townAccountId: "2",
    townName: "磁灶镇",
    townPerson: "李四",
    townMobile: "13800138002",
    status: 1,
    createTime: "2024-01-10 09:15:00",
    updateTime: "2024-01-18 16:45:00"
  },
  {
    townAccountId: "3",
    townName: "陈埭镇",
    townPerson: "王五",
    townMobile: "13800138003",
    status: 0,
    createTime: "2024-01-08 14:20:00",
    updateTime: "2024-01-22 11:30:00"
  },
  {
    townAccountId: "4",
    townName: "池店镇",
    townPerson: "赵六",
    townMobile: "13800138004",
    status: 1,
    createTime: "2024-01-05 16:45:00",
    updateTime: "2024-01-25 09:10:00"
  },
  {
    townAccountId: "5",
    townName: "东石镇",
    townPerson: "孙七",
    townMobile: "13800138005",
    status: 1,
    createTime: "2024-01-03 11:20:00",
    updateTime: "2024-01-28 15:55:00"
  }
];

//搜索参数表单
const searchForm = reactive({
  //镇街名称
  townName: null,
  //账号状态
  status: null,
  //页码
  pageNum: 1,
  //条数
  pageSize: 10,
});

//数据列表
const datatable = reactive({
  //列配置
  columns: [
    {
      title: "镇街名称",
      dataIndex: "townName",
      slotName: "townName",
      align: "center",
    },
    {
      title: "镇街联系人",
      dataIndex: "townPerson",
      align: "center",
    },
    {
      title: "镇街联系方式",
      dataIndex: "townMobile",
      align: "center",
    },
    {
      title: "镇街账号状态",
      dataIndex: "status",
      slotName: "status",
      align: "center",
      filterable: {
        filters: [
          {
            text: "禁用",
            value: "0",
          },
          {
            text: "正常",
            value: "1",
          },
        ],
        filter: (value, record) => record.status == value,
        multiple: true,
      },
    },
    {
      title: "操作",
      slotName: "operation",
      align: "center",
      width: 160,
      fixed: "right",
    },
  ],
  //加载
  loading: false,
  //数据列表
  records: [],
  //总条数
  total: 0,
});

//查询数据列表
const getPageList = (isReset = false) => {
  if (isReset) {
    searchForm.townName = null;
    searchForm.status = null;
    searchForm.pageNum = 1;
    searchForm.pageSize = 10;
  }
  datatable.loading = true;
  
  // 模拟API调用
  setTimeout(() => {
    let filteredData = [...mockTownData];
    
    // 根据搜索条件过滤数据
    if (searchForm.townName) {
      filteredData = filteredData.filter(item => 
        item.townName.includes(searchForm.townName)
      );
    }
    if (searchForm.status !== null && searchForm.status !== undefined && searchForm.status !== '') {
      filteredData = filteredData.filter(item => 
        item.status.toString() === searchForm.status.toString()
      );
    }
    
    // 分页处理
    const startIndex = (searchForm.pageNum - 1) * searchForm.pageSize;
    const endIndex = startIndex + searchForm.pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    datatable.records = paginatedData;
    datatable.total = filteredData.length;
    datatable.loading = false;
  }, 500);
};

//公共模态框
const modal = reactive({
  //是否显示
  visible: false,
  //模态框标题
  title: "镇街账号管理",
  //宽度
  width: "50%",
  //传递参数
  params: {},
  //组件名称
  component: null,
});

//添加按钮 -> 点击事件
const addBtnClick = () => {
  modal.visible = true;
  modal.title = "添加镇街账号";
  modal.width = "400px";
  modal.params = {operationType: proxy.operationType.add.type};
  modal.component = shallowRef(TownAccountEdit);
};

//表格行数据 "查看" -> 点击
const detailBtnClick = (townAccountId) => {
  modal.visible = true;
  modal.title = "查看镇街账号";
  modal.params = {
    operationType: proxy.operationType.detail.type,
    townAccountId: townAccountId,
  };
  modal.component = shallowRef(TownAccountDetail);
};

//删除按钮 -> 点击事件
const deleteBtnClick = (selectedKeys) => {
  if (selectedKeys.length === 0) {
    proxy.$msg.error("请选择要删除的镇街账号");
    return;
  }
  deleteConfirmVisible.value = true;
};

//表格行数据 "修改" -> 点击
const updateBtnClick = (townAccountId) => {
  modal.visible = true;
  modal.title = "修改镇街账号信息";
  modal.params = {
    operationType: proxy.operationType.update.type,
    townAccountId: townAccountId,
  };
  modal.component = shallowRef(TownAccountEdit);
};

//表格行数据 "删除" -> 确认
const deleteBtnOkClick = (townAccountId) => {
  // 模拟API调用
  setTimeout(() => {
    proxy.$msg.success(proxy.operationType.delete.success);
    //刷新列表
    getPageList();
  }, 500);
};

const onDeleteConfirmCancel = () => {
  deleteConfirmVisible.value = false;
  selectedKeys.value = [];
};

//删除确认弹窗 -> 确认（批量删除）
const onDeleteConfirmOK = () => {
  deleteConfirmVisible.value = false;
  let ids = [...selectedKeys.value];
  if (ids.length === 0) return;
  // 模拟批量删除API调用
  setTimeout(() => {
    proxy.$msg.success(proxy.operationType.delete.success);
    selectedKeys.value = [];
    getPageList();
  }, 500);
};

const onOk = () => {
  modal.visible = false;
  //查询数据列表
  getPageList();
};

//模态框 -> 取消
const onCancel = () => {
  modal.visible = false;
};

//模态框 -> 编辑
const onEdit = (townAccountId) => {
  modal.visible = false;
  updateBtnClick(townAccountId);
};

//查询数据列表
getPageList();
</script>

<style scoped></style>